//
//  UserVideoUploadViewController.m
//  ChatForHot
//
//  Created by wr on 2018/10/16.
//  Copyright © 2018年 FLY. All rights reserved.
//

#import "UserVideoUploadViewController.h"
#import "UPhotoBottomView.h"
#import "UPhotoListView.h"
#import "HCPhotoCell.h"
#import "HCPhotoCameraCell.h"
#import "HCPhotoManager.h"
#import "HOTCHATVideoCaptureViewController.h"

@interface UserVideoUploadViewController ()<UICollectionViewDataSource,UICollectionViewDelegate,UINavigationControllerDelegate, UIImagePickerControllerDelegate,UPhotoBottomDelegate>

@property(nonatomic,strong) UICollectionView *HOTCHATphotoCollectionView;
@property(nonatomic,strong) UIBarButtonItem *HOTCHATconfirmBar;
@property(nonatomic,strong) NSArray *dataArray;
@property(nonatomic,strong) NSMutableArray *selectArray;
@property(nonatomic,assign) NSInteger HOTCHATcellwidth;
@property(nonatomic,strong) UPhotoBottomView *HOTCHATbottomView;
@property(nonatomic,strong) UPhotoListView *HOTCHATlistview;
@property(nonatomic,strong) NSArray *photoListArray;
@property(nonatomic,assign) BOOL isSendPhoto;
@property(nonatomic,assign) NSInteger selectedRow;
@end

@implementation UserVideoUploadViewController

- (void)HOTCHATdidInitialized {
    [super HOTCHATdidInitialized];
    
    float cwidth = CGRectGetWidth(self.view.frame);
    if (self.HOTCHATcellwidth == 0) {
        self.HOTCHATcellwidth = (cwidth - 8 - 3.5 * 4) / 5;
        if (self.HOTCHATcellwidth < 100) {
            self.HOTCHATcellwidth = (cwidth - 8 - 3.5 * 3) / 4;
        }
        if (self.HOTCHATcellwidth < 100) {
            self.HOTCHATcellwidth = (cwidth - 8 - 3.5 * 2) / 3;
        }
    }
    self.selectArray = [[NSMutableArray alloc] init];
}

- (void)HOTCHATInsertSubViews {
    [super HOTCHATInsertSubViews];
    
    self.HOTCHATconfirmBar = [[UIBarButtonItem alloc] initWithTitle:NSLocalizedString(@"userPhoto5", nil) style:(UIBarButtonItemStylePlain) target:self action:@selector(HOTCHATconfirmAction)];
    
    self.navigationItem.rightBarButtonItem = self.HOTCHATconfirmBar;
    
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    [layout setScrollDirection:UICollectionViewScrollDirectionVertical];
    self.HOTCHATphotoCollectionView = [[UICollectionView alloc] initWithFrame:self.view.bounds collectionViewLayout:layout];
    self.HOTCHATphotoCollectionView.dataSource = self;
    self.HOTCHATphotoCollectionView.delegate = self;
    self.HOTCHATphotoCollectionView.alwaysBounceVertical = YES;
    [self.HOTCHATphotoCollectionView registerClass:[HCPhotoCell class] forCellWithReuseIdentifier:@"HCPhotoCell"];
    [self.HOTCHATphotoCollectionView registerClass:[HCPhotoCameraCell class] forCellWithReuseIdentifier:@"HCPhotoCameraCell"];
    self.HOTCHATphotoCollectionView.showsHorizontalScrollIndicator = NO;
    self.HOTCHATphotoCollectionView.backgroundColor = [UIColor clearColor];
    [self.view addSubview:self.HOTCHATphotoCollectionView];
    
    self.HOTCHATbottomView = [[UPhotoBottomView alloc] init];
    self.HOTCHATbottomView.photoName = @"";
    self.HOTCHATbottomView.delegate = self;
    [self.view addSubview:self.HOTCHATbottomView];
    
    self.HOTCHATlistview = [[UPhotoListView alloc] init];
    self.HOTCHATlistview.delegate = self;
}

- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];
    
    [self.HOTCHATphotoCollectionView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.left.right.top.equalTo(self.view);
        make.bottom.equalTo(self.HOTCHATbottomView.mas_top);
    }];
    [self.HOTCHATbottomView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.equalTo(self.view);
        make.height.mas_equalTo(50);
    }];
}

- (void)HOTCHATsetNavigationItemsIsInEditMode:(BOOL)isInEditMode animated:(BOOL)animated {
    [super HOTCHATsetNavigationItemsIsInEditMode:isInEditMode animated:animated];
    
    self.title = NSLocalizedString(@"selGp2", nil);
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self getDeviceAllPhotos];
}

- (void)getDeviceAllPhotos {
    @weakify(self)
    [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
        dispatch_async(dispatch_get_main_queue(), ^{
            @strongify(self)
            if (self.dataArray.count == 0 && status == PHAuthorizationStatusAuthorized) {
                [self HOTCHATgetAllPhotos];
            }
        });
    }];
    
    if ([PHPhotoLibrary authorizationStatus] == PHAuthorizationStatusDenied) {
    }else{
        [self HOTCHATgetAllPhotos];
    }
}

#pragma mark UICollectionDatasource

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return self.dataArray.count + 1;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.row == 0) {
        HCPhotoCameraCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"HCPhotoCameraCell" forIndexPath:indexPath];
        return cell;
    }
    HCPhotoCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"HCPhotoCell" forIndexPath:indexPath];
    id entity = self.dataArray[indexPath.row - 1];
    cell.entity = entity;
    cell.isVideo = YES;
    BOOL isSelected = [self HOTCHATisSelectedPhoto:entity];
    cell.isSelected = isSelected;
    if (self.isSendPhoto) {
        if (isSelected) {
            self.selectedRow = indexPath.row;
        }
    }
    return cell;
}
#pragma mark UICollectionview Delegate

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.row == 0) {
        [collectionView deselectItemAtIndexPath:indexPath animated:YES];
        [self HOTCHATopenCamera];
    }else{
        HCPhotoCell *cell = (HCPhotoCell *)[collectionView cellForItemAtIndexPath:indexPath];
        if (cell.isSelected) {
            [self.selectArray removeObject:cell.entity];
            cell.isSelected = NO;
        }else{
            if (self.selectArray.count > 0) {
                [self.selectArray removeAllObjects];
                if (self.selectedRow > 0 && self.selectedRow <= self.dataArray.count) {
                    NSIndexPath *ipath = [NSIndexPath indexPathForItem:self.selectedRow inSection:0];
                    [self.HOTCHATphotoCollectionView reloadItemsAtIndexPaths:@[ipath]];
                }
            }
            self.selectedRow = indexPath.row;
            [self.selectArray addObject:cell.entity];
            cell.isSelected = YES;
        }
    }
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section{
    return 3.5;
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section{
    return 3.5;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    return CGSizeMake(self.HOTCHATcellwidth, self.HOTCHATcellwidth);
}

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{
    return UIEdgeInsetsMake(4, 4, 4, 4);
}

#pragma mark - Actions

- (void)HOTCHATconfirmAction{
    @weakify(self);
    void (^uploadBlock)(void) = ^{
        @strongify(self);
        if (self.delegate && [self.delegate respondsToSelector:@selector(HOTCHATselectedVideoArray:)]) {
            [self.delegate HOTCHATselectedVideoArray:self.selectArray];
        }
        [self.navigationController popViewControllerAnimated:YES];
    };
    
    if (!self.isSendPhoto) {
        if (self.selectArray.count > 0) {
            HCAssetModel *selModel = [self.selectArray firstObject];
            PHAsset *phasset = selModel.asset;
            NSInteger times = [phasset duration];
            
            if (times > HOTCHATMaxVideoTimes) {
                [NetWorkTool HOTCHATshowMessage:@"Video can't exceed 15 seconds and less than 50M"];
                return;
            }
            [self HOTCHATgetvideosize:phasset sizeBlock:^(float zise) {
                if (zise > HOTCHATMaxVideoLength){
                    [NetWorkTool HOTCHATshowMessage:@"Video can't exceed 15 seconds and less than 50M"];
                }else{
                    uploadBlock();
                }
                NSLog(@"22%@",[NSThread currentThread]);
            }];
            return;
        }
    }
    uploadBlock();
}

- (void)HOTCHATgetvideosize:(id)phasset sizeBlock:(void (^)(float zise))sizeBlock{
    PHVideoRequestOptions *options = [[PHVideoRequestOptions alloc] init];
    options.version = PHVideoRequestOptionsVersionOriginal;
    
    [[PHImageManager defaultManager] requestAVAssetForVideo:phasset options:options resultHandler:^(AVAsset *asset, AVAudioMix *audioMix, NSDictionary *info) {
        NSNumber *size;
        if ([asset isKindOfClass:[AVURLAsset class]]) {
            AVURLAsset* urlAsset = (AVURLAsset*)asset;
            [urlAsset.URL getResourceValue:&size forKey:NSURLFileSizeKey error:nil];
            NSLog(@"size is %f",[size floatValue]/(1024.0*1024.0)); //size is
        }
        
        dispatch_async(dispatch_get_main_queue(), ^{
            if (sizeBlock) {
                sizeBlock([size floatValue]);
            }
        });
    }];
}

- (BOOL)HOTCHATisSelectedPhoto:(id)entity{
    if (self.selectArray.count == 0) {
        return NO;
    }
    NSString *id1 = [[HCPhotoManager shareManager] getAssetIdentifier:entity];
    NSString *id2 = nil;
    for (id sEntity in self.selectArray) {
        id2 = [[HCPhotoManager shareManager] getAssetIdentifier:sEntity];
        if ([id1 isEqualToString:id2]) {
            return YES;
        }
    }
    return NO;
}

#pragma -mark get photo

- (void)HOTCHATgetAllPhotos{
    @weakify(self)
    [[HCPhotoManager shareManager] getAllAlbums:self.isVideo allowPickingImage:!self.isVideo completion:^(NSArray<HCAlbumModel *> *modelsll) {
        @strongify(self)
        self.photoListArray = modelsll;
        if (modelsll.count > 0) {
            [self HOTCHATgetPhotos:[modelsll firstObject]];
        }
    }];
}

- (void)HOTCHATgetPhotos:(HCAlbumModel *)HCam{
    @weakify(self)
    self.HOTCHATbottomView.photoName = HCam.name;
    [[HCPhotoManager shareManager] getAssetsFromFetchAlbumModel:HCam allowPickingVideo:self.isVideo allowPickingImage:!self.isVideo completion:^(NSArray<HCAssetModel *> *models) {
        @strongify(self)
        self.dataArray = [[models reverseObjectEnumerator] allObjects];
        self.selectedRow = -1;
        [self.HOTCHATphotoCollectionView performSelectorOnMainThread:@selector(reloadData) withObject:self waitUntilDone:NO];
    }];
}

- (void)HOTCHATsetListShow{
    self.HOTCHATbottomView.isShowList = YES;
    [self.HOTCHATlistview HOTCHATshowInView:self.view.window.rootViewController.view array:self.photoListArray];
}

- (void)HOTCHAThiddenListView{
    [self.HOTCHATlistview HOTCHATcloseListView];
    self.HOTCHATbottomView.isShowList = NO;
}

- (void)HOTCHATcloseListView{
    self.HOTCHATbottomView.isShowList = NO;
}

#pragma mark - videoRecord

- (void)HOTCHATopenCamera {
    HOTCHATVideoCaptureViewController *cap = [[HOTCHATVideoCaptureViewController alloc] init];
    cap.callBackBlock = ^(BOOL success, id result) {
        if (success) {
            if (self.delegate && [self.delegate respondsToSelector:@selector(HOTCHATselectedVideoArray:)]) {
                [self.selectArray addObject:result];
                [self.delegate HOTCHATselectedVideoArray:self.selectArray];
            }
            [self.navigationController popViewControllerAnimated:YES];
        }
    };
    [self presentViewController:cap animated:YES completion:nil];
}

@end
